import { SetPrinterComponent } from './../setPrinter/setprinter.component';
import { NavController } from 'ionic-angular';
import { MdSnackBar } from '@angular/material';
import { GrowlMessageType, MessageBoxService } from './../../../../component/messageBoxService';
import { DeviceManager } from './../../../../common/mpj-deviceCenter/src/deviceManager';
import { PrintService } from './../../../../service/print.service';
import { Component } from '@angular/core';
import { NavigateService } from "../../../../service/navigate.service";

@Component({
    selector: 'add-printer',
    templateUrl: './addPrinter.component.html',
    styleUrls: ['./addPrinter.component.scss']
})

export class AddPrinterComponent {
    printerIP: string = ""; //打印机ip
    isLoading: boolean = false; //是否在查找中
    searchFailed: boolean = false;
    linkType: string = "wifi";
    port: number = 9100; //打印机地址端口
    deviceType = "receipt-printer"; //打印机类型
    usage = "sales-receipt"; //打印机用途  "sales-receipt": 客户小票打印机，"kitchen-receipt": 厨房小票打印机，"kitchen-label"：制作标签打印机
    //是否带切刀
    autoCut: boolean = false;
    //是否连接钱箱
    cashboxConnected: boolean = false;
    // 打印机指令
    instructionSet;
    //打印机宽度
    paperSize;
    //打印机尾部走纸行数
    paperScrollRows;
    //厨房打印方案
    kitchenSolutionId: string = "all";
    findPrinters: any = [];
    printerManager;
    adsServer;
    constructor(
        private router: NavigateService,
        private printSvr: PrintService,
        private msgSvr: MessageBoxService,
        public snackBar: MdSnackBar,
        public navCtrl: NavController
    ) { }

    ionViewWillEnter() {
        this.router.registGoBack(() => {
            let backBtn = document.getElementById("addprinter-back-btn");
            if (backBtn) {
                backBtn.click();
            }
        });
        this.printerManager = DeviceManager.Current.getManagerByType("printerManager");
        if (!this.printerManager) {
            console.log("打印管理器未初始化");
            return;
        }

        //设置默认值
        this.autoCut = false;
        this.cashboxConnected = false;
        this.instructionSet = this.printerManager.instructionSets[0];
        this.paperSize = this.printerManager.selectPageSizes[0];
        this.paperScrollRows = this.printerManager.paperScrollRows[3];
        this.adsServer = this.printSvr.adsServer;
    }

    goBack() {
        // return this.router.navigate(["printer"]);
        this.navCtrl.pop({ animate: false });
    }
    /**
     * 查找打印机
     */
    searchPrinter() {
        let ipRegExp = new RegExp("^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
        let boo = ipRegExp.test(this.printerIP);
        if (!boo) {
            this.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, "输入的IP地址有误，请重新输入");
            this.printerIP = "";
            return;
        }
        this.isLoading = true;
        this.searchFailed = false;
        let info = {
            ip: this.printerIP,
            port: this.port
        }
        let infoStr = JSON.stringify(info);
        let findParams: any = {
            token: this.router.Token,
            info: infoStr,
            type: this.linkType,
            storeId: this.router.CurrentStore.id
        }
        this.printerManager.findDevice(this.adsServer.url + "/printer/find", findParams)
            .then((result) => {
                console.log(result.msg);
                this.isLoading = false;
                if (result.status == 200 && result.data && result.data.length) {
                    result.data.forEach(element => {
                        let printer: any = {};
                        let printerInfo: any = {};
                        printer.address = element.address;
                        printer.manufacturer = element.manufacturer;
                        printer.productName = element.productName;
                        printer.type = element.type;
                        printer.deviceInfo = element.deviceInfo;
                        printer.usage = this.usage;
                        printer.instructionSet = this.instructionSet.value;
                        printer.autoCut = this.autoCut;
                        printer.cashboxConnected = this.cashboxConnected;
                        printer.paperSize = this.paperSize.value;
                        printer.paperScrollRows = this.paperScrollRows.value;
                        printer.deviceType = this.deviceType;

                        this.printerManager.saveFindDevice(printer);
                    });
                    // this.router.navigate(["setPrinter"]);
                    this.navCtrl.push(SetPrinterComponent, {}, { animate: false });
                } else {
                    this.searchFailed = true;
                }
            })
            .catch((error) => {
                console.log(error);
            });
    }

    searchAgain() {
        this.searchPrinter();
    }
}